package com.buba.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.buba.system.pojo.Menu;
import com.buba.system.pojo.RoleRight;
import com.buba.system.pojo.UserInfo;
import com.buba.system.service.MenuService;
import com.buba.system.service.impl.MenuServiceImpl;
import com.buba.util.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@WebServlet("/MenuServlet")
public class MenuServlet extends BaseServlet {
    MenuService menuService = new MenuServiceImpl();
    @Override
    public void doRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String flag = request.getParameter("flag");
        if ("selMenu".equals(flag))
            this.selMenu(request,response);
        if ("selAll".equals(flag))
            this.selAll(request,response);
        if ("selRoleRight".equals(flag))
            this.selRoleRight(request,response);
        if ("addRoleRight".equals(flag))
            this.addRoleRight(request,response);
    }


    private void addRoleRight(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String nodeId = request.getParameter("NodeId");
        Object[] o = JSONArray.parseArray(nodeId).toArray();
        String roleId = request.getParameter("roleId");
        menuService.addRoleRight(o,roleId);
        response.getWriter().write(1+"");
    }

    private void selRoleRight(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, String> param = getParam(request);
        List<RoleRight> list = menuService.selRoleRight(param.get("roleId"));
        response.getWriter().write(JSON.toJSONString(list));

    }

    private void selAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        UserInfo user = (UserInfo) session.getAttribute("login");
        int roleId = user.getRoleId();
        //调用业务层菜单方法
        List<Menu> list = menuService.selMenu1();
        //将结果集返回给浏览器
        response.getWriter().write(JSON.toJSONString(list));
    }

    /**
     *查询菜单
     * @param request
     * @param response
     */
    private void selMenu(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        System.out.println("连接成功");
        HttpSession session = request.getSession();
        UserInfo user = (UserInfo) session.getAttribute("login");
        int roleId = user.getRoleId();
        //调用业务层菜单方法
        List<Menu> list = menuService.selMenu(roleId);
        //将结果集返回给浏览器
        response.getWriter().write(JSON.toJSONString(list));
    }
}
